/// 短信消息数据模型
///
/// 包含接收到的短信的所有相关信息，如内容、发送者、时间等
class SmsMessage {
  /// 短信内容
  final String body;

  /// 发送者号码
  final String address;

  /// 接收时间
  final DateTime date;

  /// 短信类型
  /// 1 = 收件箱 (接收的短信)
  /// 2 = 发件箱 (发送的短信)
  final int type;

  /// 构造函数
  const SmsMessage({
    required this.body,
    required this.address,
    required this.date,
    required this.type,
  });

  /// 从Map创建SmsMessage对象
  ///
  /// 主要用于从Android原生代码传递过来的数据中创建对象
  factory SmsMessage.fromMap(Map<String, dynamic> map) {
    // 兼容Android端发送的timestamp或date键
    int dateValue = map['timestamp'] as int? ??
        map['date'] as int? ??
        DateTime.now().millisecondsSinceEpoch;

    // 兼容不同的type值格式
    dynamic typeValue = map['type'];
    int typeInt;
    if (typeValue is String) {
      typeInt = typeValue == 'received' ? 1 : 2;
    } else {
      typeInt = typeValue as int? ?? 1;
    }

    return SmsMessage(
      body: map['body'] as String? ?? '',
      address: map['address'] as String? ?? '',
      date: DateTime.fromMillisecondsSinceEpoch(dateValue),
      type: typeInt,
    );
  }

  /// 转换为Map
  ///
  /// 用于将对象序列化，便于传递和存储
  Map<String, dynamic> toMap() {
    return {
      'body': body,
      'address': address,
      'date': date.millisecondsSinceEpoch,
      'type': type,
    };
  }

  /// 转换为JSON字符串
  @override
  String toString() {
    return 'SmsMessage{'
        'body: $body, '
        'address: $address, '
        'date: $date, '
        'type: $type'
        '}';
  }

  /// 相等性比较
  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;

    return other is SmsMessage &&
        other.body == body &&
        other.address == address &&
        other.date == date &&
        other.type == type;
  }

  /// 哈希码
  @override
  int get hashCode {
    return body.hashCode ^ address.hashCode ^ date.hashCode ^ type.hashCode;
  }

  /// 是否为接收的短信
  bool get isReceived => type == 1;

  /// 获取时间戳（毫秒）
  int get timestamp => date.millisecondsSinceEpoch;

  /// 格式化的日期时间字符串
  String get formattedDate {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} '
        '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}:${date.second.toString().padLeft(2, '0')}';
  }

  /// 简短的时间显示
  String get shortTimeDisplay {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'just now';
    }
  }

  /// 是否为发送的短信
  bool get isSent => type == 2;
}
